package cn.cylinder.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * ProjectName: config-master &lt;br/&gt;
 * Function: ${TODO} ADD FUNCTION. &lt;br/&gt;
 * date:2015/12/11 0011 9:43
 *
 * @author cylinder
 * @since JDK 1.7
 */
@Controller
@RequestMapping("image")
public class ImageAgent {

    private static final Logger log = LoggerFactory.getLogger(IndexAgent.class);

    private static final String IMAGE_PATH = "d:/image/";
    @RequestMapping("upload")
    @ResponseBody
    public String index(MultipartHttpServletRequest multipartRequest) throws Exception{
        log.info("upload image");
        // MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("uploadFile");
        String filename = UUID.randomUUID().toString();
        InputStream input = file.getInputStream();

        File source = new File(IMAGE_PATH+filename);
        file.transferTo(source);
        String error = "";
        String msg = "";
        String imgurl = "image/show/"+filename;
        StringBuilder sb = new StringBuilder();
        sb.append("<img id=\"imgUpload\" src=\"" + imgurl+"\" />");
        return sb.toString();
    }

    @RequestMapping("show/{name}")
    public void showImage(HttpServletRequest request,HttpServletResponse response,@PathVariable String name)throws Exception{
        response.setContentType("text/html; charset=UTF-8");
        response.setContentType("image/jpeg");

        String newpath = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        String absolutePath = IMAGE_PATH + newpath;
        FileInputStream fis = new FileInputStream(absolutePath);
        OutputStream os = response.getOutputStream();
        try
        {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
    }
}
